<!DOCTYPE html>




<html class="theme-next gemini" lang="zh-Hans">
<head><meta name="generator" content="Hexo 3.9.0">
  <meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform">
<meta http-equiv="Cache-Control" content="no-siteapp">
















  
  
    
  
  <link href="https://cdn.staticfile.org/fancybox/3.5.7/jquery.fancybox.min.css" rel="stylesheet" type="text/css">




  
  
  
  

  
    
    
  

  
    
      
    

    
  

  

  
    
      
    

    
  

  
    
      
    

    
  

  
    
    
    <link href="//fonts.googleapis.com/css?family=Monda:300,300italic,400,400italic,700,700italic|Roboto Slab:300,300italic,400,400italic,700,700italic|Lobster Two:300,300italic,400,400italic,700,700italic|Source Code Pro:300,300italic,400,400italic,700,700italic&subset=latin,latin-ext" rel="stylesheet" type="text/css">
  






  

<link href="https://cdn.staticfile.org/font-awesome/4.6.2/css/font-awesome.css" rel="stylesheet" type="text/css">

<link href="/css/main.css?v=6.0.0" rel="stylesheet" type="text/css">


  <link rel="apple-touch-icon" sizes="180x180" href="http://tva3.sinaimg.cn/crop.206.47.515.515.180/709d5819jw8f4k1tlmnsij20pr0gytdx.jpg?v=6.0.0">


  <link rel="icon" type="image/png" sizes="32x32" href="http://tva3.sinaimg.cn/crop.206.47.515.515.180/709d5819jw8f4k1tlmnsij20pr0gytdx.jpg?v=6.0.0">


  <link rel="icon" type="image/png" sizes="16x16" href="http://tva3.sinaimg.cn/crop.206.47.515.515.180/709d5819jw8f4k1tlmnsij20pr0gytdx.jpg?v=6.0.0">


  <link rel="mask-icon" href="http://tva3.sinaimg.cn/crop.206.47.515.515.180/709d5819jw8f4k1tlmnsij20pr0gytdx.jpg?v=6.0.0" color="#222">





  <meta name="keywords" content="vps, java, python, golang, springmvc">




  


  <link rel="alternate" href="/atom.xml" title="张恒的网络日志" type="application/atom+xml">






<meta name="keywords" content="java, python, go, 技术, 学习笔记, spring">
<meta property="og:type" content="website">
<meta property="og:title" content="张恒的网络日志">
<meta property="og:url" content="http://blog.gavinzh.com/404.html">
<meta property="og:site_name" content="张恒的网络日志">
<meta property="og:locale" content="zh-Hans">
<meta property="og:updated_time" content="2020-01-05T08:52:36.912Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="张恒的网络日志">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Gemini',
    version: '6.0.0',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":true,"scrollpercent":true,"onmobile":false},
    fancybox: true,
    fastclick: true,
    lazyload: true,
    tabs: true,
    motion: {"enable":false,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://blog.gavinzh.com/404.html">





  <title>StringFormatter，一个javascript编写的字符串格式化库 | 张恒的网络日志</title>
  




<script>
  (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
            (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
          m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
  })(window,document,'script','https://www.google-analytics.com/analytics.js','ga');
  ga('create', 'UA-98061925-1', 'auto');
  ga('send', 'pageview');
</script>





</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"> <div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">张恒的网络日志</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <h1 class="site-subtitle" itemprop="description">Zhang Heng's WebSite Blog</h1>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br>
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br>
            
            关于
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br>
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br>
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br>
            
            归档
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br>
            
            搜索
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off" placeholder="搜索..." spellcheck="false" type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://blog.gavinzh.com/2017/05/03/javascript-stringformatter-tutorial/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="Gavin Zhang">
      <meta itemprop="description" content>
      <meta itemprop="image" content="https://avatars3.githubusercontent.com/u/5567916">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="张恒的网络日志">
    </span>

    
      <header class="post-header">

        
        
          <h2 class="post-title" itemprop="name headline">StringFormatter，一个javascript编写的字符串格式化库</h2>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2017-05-03T10:11:00+00:00">2017-05-03</time>
            

            

            
          </span>

          
            <span class="post-category">
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/笔记/" itemprop="url" rel="index">
                    <span itemprop="name">笔记</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
              <span class="post-comments-count">
                <span class="post-meta-divider">|</span>
                <span class="post-meta-item-icon">
                  <i class="fa fa-comment-o"></i>
                </span>
                <a href="/2017/05/03/javascript-stringformatter-tutorial/#comments" itemprop="discussionUrl">
                  <span class="post-comments-count disqus-comment-count" data-disqus-identifier="2017/05/03/javascript-stringformatter-tutorial/" itemprop="commentCount"></span>
                </a>
              </span>
            
          

          
          
             <span id="/2017/05/03/javascript-stringformatter-tutorial/" class="leancloud_visitors" data-flag-title="StringFormatter，一个javascript编写的字符串格式化库">
               <span class="post-meta-divider">|</span>
               <span class="post-meta-item-icon">
                 <i class="fa fa-eye"></i>
               </span>
               
                 <span class="post-meta-item-text">阅读次数&#58;</span>
               
                 <span class="leancloud-visitors-count"></span>
             </span>
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <p><code>StringFormatter JS</code>是一个js编写的可扩展的javascript字符串格式化库，它的功能远远超出了ECMA6标准所规定的字符串格式化规则。</p>
<p>它的内置转换功能如下:</p>
<ol>
<li>字符串</li>
<li>所有数值类型包括整数，小数，十六进制，八进制，百分比和金融符号以及对<code>NaN</code>和<code>Infinity</code>的特殊处理</li>
<li>布尔型</li>
<li>数组和对象</li>
<li>函数</li>
<li>日期/时间</li>
<li>应用CSS样式</li>
<li>有条件的格式化</li>
</ol>
<a id="more"></a>

<p>举一个例子：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">format(<span class="string">"The time is &#123;Date:&#123;format:'hh:mm'&#125;&#125; and I have &#123;number:&#123;fixed: 2,currency:'$'&#125;&#125;."</span>,</span><br><span class="line">       <span class="keyword">new</span> <span class="built_in">Date</span>(<span class="string">'2015-03-13T10:01:27.284Z'</span>),</span><br><span class="line">       <span class="number">50.25</span>)</span><br></pre></td></tr></table></figure>

<p>返回结果如下：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">The time is 10:01 and I have $50.25.</span><br></pre></td></tr></table></figure>

<!--more-->

<h3 id="例子"><a href="#例子" class="headerlink" title="例子"></a>例子</h3><table>
<thead>
<tr>
<th>格式化</th>
<th>结果</th>
</tr>
</thead>
<tbody><tr>
<td>Format</td>
<td>Result</td>
</tr>
<tr>
<td>format(‘{number}’,2)</td>
<td>2</td>
</tr>
<tr>
<td>format(‘{number: {fixed: 2}}’,2)</td>
<td>2.00</td>
</tr>
<tr>
<td>format(‘{number: {precision: 3}}’,2)</td>
<td>2.00</td>
</tr>
<tr>
<td>format(‘{number: {as: ‘%’}}’,2)</td>
<td>2%</td>
</tr>
<tr>
<td>format(‘{number: {as: ‘h’}}’,255)</td>
<td>0xff</td>
</tr>
<tr>
<td>format(‘{number: {as: ‘h’}}’,-255)</td>
<td>-0xff</td>
</tr>
<tr>
<td>format(‘{number: {as: ‘o’}}’,255)</td>
<td>0377</td>
</tr>
<tr>
<td>format(‘{number: {as: ‘o’}}’,-255)</td>
<td>-0377</td>
</tr>
<tr>
<td>format(‘{number: {as: ‘b’}}’,255)</td>
<td>11111111</td>
</tr>
<tr>
<td>format(‘{number: {as: ‘b’}}’,-255)</td>
<td>-11111111</td>
</tr>
<tr>
<td>format(‘{number: {ifNaN: ‘Not A Number’}}’,null)</td>
<td>Not A Number</td>
</tr>
<tr>
<td>format(‘{number: {ifInfinity: ‘Bigger Than Google<code>&lt;br&gt;</code>blog.Gavinzh.com!’}}’,null)</td>
<td>Bigger Than Google<br>blog.Gavinzh.com!</td>
</tr>
<tr>
<td>format(‘{number: {currency: ‘$’, fixed:2}}’,255)</td>
<td>$255.00</td>
</tr>
<tr>
<td>format(‘{number: {currency: ‘$’, fixed:2}}’,-255)</td>
<td>$-255.00</td>
</tr>
<tr>
<td>format(‘{number: {currency: ‘$’, fixed:2, style:(@value &lt; 0 ? ‘color:red’ : null)}}’,-255)</td>
<td>$-255.00</td>
</tr>
<tr>
<td>format(‘{number: {currency: ‘$’, fixed:2, accounting: true, style:(@value &lt; 0 ? ‘color:red’ : null)}}’,-255)</td>
<td><code>&lt;span style=&#39;color:red&#39;&gt;($255.00)&lt;/span&gt;</code></td>
</tr>
<tr>
<td>format(‘{boolean}’,true)</td>
<td>true</td>
</tr>
<tr>
<td>format(‘{boolean: {as: ‘string’}}’,true)</td>
<td>yes</td>
</tr>
<tr>
<td>format(‘{boolean: {as: ‘string’, style:(@value ? ‘color:green’ : ‘color:red’)}}’,true)</td>
<td><code>&lt;span style=&#39;color:green&#39;&gt;no&lt;/span&gt;</code></td>
</tr>
<tr>
<td>format(‘{boolean: {as: ‘number’}}’,true)</td>
<td>1</td>
</tr>
<tr>
<td>format(‘{boolean}’,2)</td>
<td>true</td>
</tr>
<tr>
<td>format(‘{boolean}’,false)</td>
<td>false</td>
</tr>
<tr>
<td>format(‘{boolean: {as: ‘string’, style:(@value ? ‘color:green’ : ‘color:red’)}}’,false)</td>
<td><code>&lt;span style=&#39;color:red&#39;&gt;no&lt;/span&gt;</code></td>
</tr>
<tr>
<td>format(‘{boolean: {as: ‘number’}}’,false)</td>
<td>0</td>
</tr>
<tr>
<td>format(‘{boolean}’,null)</td>
<td>false</td>
</tr>
<tr>
<td>format(‘{Array}’,[“a”,”b”,”c”])</td>
<td>a,b,c</td>
</tr>
<tr>
<td>format(‘{Array : {delimiter: ‘;’}}’,[“a”,”b”,”c”])</td>
<td>a;b;c</td>
</tr>
<tr>
<td>format(‘{Array : {container: [‘[‘,’]’]}}’,[“a”,”b”,”c”])</td>
<td>[a,b,c]</td>
</tr>
<tr>
<td>format(‘{Array : {container: [‘[‘,’]’], quote:true}}’,[“a”,”b”,”c”])</td>
<td>[‘a’,’b’,’c’]</td>
</tr>
<tr>
<td>format(‘{Array : {include: [0,2]}}’,[“a”,”b”,”c”])</td>
<td>a,c</td>
</tr>
<tr>
<td>format(‘{Array : {exclude: [0,2]}}’,[“a”,”b”,”c”])</td>
<td>b</td>
</tr>
<tr>
<td>format(‘{Array : {matchValue: /c/}}’,[“a”,”b”,”c”])</td>
<td>c</td>
</tr>
<tr>
<td>format(‘{Array}’,[{“v1”:”one”},2])</td>
<td>{“v1”:”one”},2</td>
</tr>
<tr>
<td>format(‘{Object}’,{“v1”:”one”,”v2”:”two”})</td>
<td>{“v1”:”one”,”v2”:”two”}</td>
</tr>
<tr>
<td>format(‘{Object: {include: [‘v1’]}}’,{“v1”:”one”,”v2”:”two”})</td>
<td>{“v1”:”one”}</td>
</tr>
<tr>
<td>format(‘{Object: {exclude: [‘v1’]}}’,{“v1”:”one”,”v2”:”two”})</td>
<td>{“v2”:”two”}</td>
</tr>
<tr>
<td>format(‘{Object: {matchValue: /one/}}’,{“v1”:”one”,”v2”:”two”})</td>
<td>{“v1”:”one”}</td>
</tr>
<tr>
<td>format(‘{Date: {format: ‘dddd, MMMM Do, YYYY’}}’,new Date(“2005-08-01T17:01:01.500Z”))</td>
<td>Monday, August 1st, 2005</td>
</tr>
<tr>
<td>format(‘{Date: {format: ‘YYYY MM DD hh:mm:ss:SSS A’}}’,new Date(“2005-08-01T17:01:01.500Z”))</td>
<td>2005 08 01 01:01:01:500 PM</td>
</tr>
<tr>
<td>format(‘{Date: {format: ‘U’}}’,new Date(“2005-08-01T17:01:01.500Z”))</td>
<td>Mon, 01 Aug 2005 17:01:01 UTC</td>
</tr>
<tr>
<td>format(‘{Date: {format: ‘G’}}’,new Date(“2005-08-01T17:01:01.500Z”))</td>
<td>Mon, 01 Aug 2005 17:01:01 GMT</td>
</tr>
<tr>
<td>format(‘{Date: {format: ‘I’}}’,new Date(“2005-08-01T17:01:01.500Z”))</td>
<td>2005-08-01T17:01:01.500Z</td>
</tr>
<tr>
<td>format(‘{Date: {format: ‘L’}}’,new Date(“2005-08-01T17:01:01.500Z”))</td>
<td>8/1/2005, 1:01:01 PM</td>
</tr>
<tr>
<td>format(‘{Function: {format: ‘N’}}’,function MyFunction(arg1,arg2) { return 1;})</td>
<td>MyFunction</td>
</tr>
<tr>
<td>format(‘{Function: {format: ‘N’}}’,function (arg1,arg2) { return 1;})</td>
<td>anonymous</td>
</tr>
<tr>
<td>format(‘{Function: {format: ‘n’}}’,function (arg1,arg2) { return 1;})</td>
<td></td>
</tr>
<tr>
<td>format(‘{Function: {format: ‘h’}}’,function MyFunction(arg1,arg2) { return 1;})</td>
<td>function MyFunction(arg1,arg2)</td>
</tr>
<tr>
<td>format(‘{Function: {format: ‘a’}}’,function MyFunction(arg1,arg2) { return 1;})</td>
<td>arg1, arg2</td>
</tr>
<tr>
<td>format(‘{Function: {format: ‘l’}}’,function MyFunction(arg1,arg2) { return 1;})</td>
<td>2</td>
</tr>
<tr>
<td>format(‘{Function: {format: ‘b’}}’,function MyFunction(arg1,arg2) { return 1;})</td>
<td>return 1;</td>
</tr>
</tbody></table>
<h3 id="通用使用方法"><a href="#通用使用方法" class="headerlink" title="通用使用方法"></a>通用使用方法</h3><p><code>StringFormatter</code> 是一个单例化的类，他会在<code>stringformatter.js</code>加载完成后自动实例化。</p>
<p>字符串的格式化是通过函数调用完成的。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">StringFormatter.format(&lt;format string&gt;,vargs...).</span><br></pre></td></tr></table></figure>

<p>你还有一个选择，当使用<code>StringFormatter.polyfill()</code>方法后，String字符串类将会被加入一个原型方法用来支持<code>&lt;format string&gt;.format(vargs...).</code>。</p>
<p>这个<code>&lt;format string&gt;</code>可以是任何合法的javascript字符串，同时，也支持JSON对象：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">eg:</span><br><span class="line">&#123;number: &#123;fixed:3, ifNaN:&apos;&apos;, currency: &apos;$&apos;, accounting:true&#125;&#125;</span><br></pre></td></tr></table></figure>

<h3 id="特殊的类型格式化"><a href="#特殊的类型格式化" class="headerlink" title="特殊的类型格式化"></a>特殊的类型格式化</h3><h4 id="字符串"><a href="#字符串" class="headerlink" title="字符串"></a>字符串</h4><p>字符串<code>string</code>没有特别的用法，只需要使用<code>{string}</code>即可。</p>
<h4 id="数值类型"><a href="#数值类型" class="headerlink" title="数值类型"></a>数值类型</h4><p>数值<code>number</code>可以采用一下格式参数：</p>
<ul>
<li><p>fixed: <code>&lt;number&gt;</code> - 返回一个带固定长度小数的字符串, e.g. <code>number: {fixed: 2}}</code>.</p>
</li>
<li><p>precision: - 返回一个带指定精度数字的字符串, e.g. <code>{number: {precision: 2}}</code>.</p>
</li>
<li><p>ifNaN: <code>&lt;string&gt;</code> - 如果出现 <code>NaN</code> 则用 <code>&lt;string&gt;</code> 替换.</p>
</li>
<li><p>ifInfinity: <code>&lt;string&gt;</code> - 如果是无限值 <code>Infinity</code> 则用 <code>&lt;string&gt;</code> 代替.</p>
</li>
<li><p>as: <code>&lt;char&gt;</code> - 返回一个和 <code>&lt;char&gt;</code> 有关系的格式化后的字符串. 支持 <code>&lt;char&gt;</code> 值的char有： <code>&quot;%&quot;</code> 百分比, <code>&quot;h&quot;</code> 十六进制, <code>&quot;o&quot;</code> 八进制, <code>&quot;b&quot;</code> 二进制, e.g. <code>{number: {as: &quot;%&quot;, fixed:2}}</code> &gt;&gt;&gt; <code>##.##%</code>.</p>
</li>
<li><p>currency: <code>&lt;char&gt;</code> 返回一个数值前面带金融符号 <code>&lt;char&gt;</code>.</p>
</li>
<li><p>accounting: <code>&lt;boolean&gt;</code> - 如果 <code>&lt;boolean&gt;===true</code> 或者数值为负数，返回指定的字符串.</p>
</li>
</ul>
<p>最后，<code>{number}</code>是最基本的格式化格式。</p>
<h4 id="布尔类型"><a href="#布尔类型" class="headerlink" title="布尔类型"></a>布尔类型</h4><p>布尔类型的特殊转换主要依靠<code>as</code>来实现：</p>
<ul>
<li><code>{boolean}</code> - 结果是 “true” or “false”.</li>
<li><code>{boolean: {as: &quot;string&quot;}}</code> - 结果是 “yes” or “no”.</li>
<li><code>{boolean: {as: &quot;number&quot;}}</code> - 结果是 “1” or “0”.</li>
</ul>
<p>在javascript中，有<code>0,null,false,undefined</code>会被理解为false，其他会被理解为true。</p>
<h4 id="对象类型"><a href="#对象类型" class="headerlink" title="对象类型"></a>对象类型</h4><p>对象类型会被转为json字符串。</p>
<ul>
<li>include: <code>&lt;Array&gt;</code> - 返回的json字符串中的key都在 <code>&lt;Array&gt;</code>中.</li>
<li>exclude: <code>&lt;Array&gt;</code> - 返回的json字符串中的key都不在 <code>&lt;Array&gt;</code>中.</li>
<li>matchValue: <code>&lt;RegExp&gt;</code> - 返回的json字符串中的key都应在 <code>&lt;RegExp&gt;</code>正则中.</li>
</ul>
<p>如果key是<code>Object</code>,则会被当作<code>object</code>。</p>
<h4 id="数组类型"><a href="#数组类型" class="headerlink" title="数组类型"></a>数组类型</h4><p>数组的格式化将会返回每一个对象。有以下配置参数:</p>
<ul>
<li><p>delimiter: <code>&lt;string&gt;</code> - 返回一个以<code>&lt;string&gt;</code>分隔开的包含所有数组对象的字符串。 默认的分隔符是逗号<code>&quot;,&quot;</code>[原文是空格，实际经测试是逗号] 。</p>
</li>
<li><p>container: <code>[&lt;start string&gt;,&lt;stop string&gt;]</code> - 返回的字符串被 <code>&lt;start string&gt;</code> 和 <code>&lt;stop string&gt;</code>所包裹. 默认的container是 [“”,””].</p>
</li>
<li><p>quote: <code>&lt;boolean&gt;</code> - 如果值是true，返回的每个元素都会被<code>&#39;</code>包裹.</p>
</li>
<li><p>include: <code>&lt;Array&gt;</code> - 如果数组中的元素在 <code>&lt;Array&gt;</code>中，才会被格式化出来.</p>
</li>
<li><p>exclude: <code>&lt;Array&gt;</code> - 如果数组元素不在 <code>&lt;Array&gt;</code>中，会被格式化.</p>
</li>
<li><p>matchValue: <code>&lt;RegExp&gt;</code> - 如果元素符合 <code>&lt;RegExp&gt;</code>正则，才会被格式化.</p>
</li>
</ul>
<h4 id="函数类型"><a href="#函数类型" class="headerlink" title="函数类型"></a>函数类型</h4><p> <code>&#39;function&#39;</code>类型会返回函数结果或者源码内容以及入参属性，它提供了一个属性<code>format</code>来决定格式化的方式。 </p>
<ul>
<li><p><code>{function}</code> - 返回整个函数代码.</p>
</li>
<li><p><code>{function: {format: &quot;v&quot;}}</code> - 返回函数的运行结果，这个方式仅当函数没有入参时才可以使用.</p>
</li>
<li><p><code>{function: {format: &quot;h&quot;}}</code> - 返回函数定义的头部信息，例如他的名字和入参名.</p>
</li>
<li><p><code>{function: {format: &quot;a&quot;}}</code> - 返回函数的入参名，不包含括号.</p>
</li>
<li><p><code>{function: {format: &quot;b&quot;}}</code> - 返回函数内容，不包括大括号.</p>
</li>
<li><p><code>{function: {format: &quot;l&quot;}}</code> - 返回入参的个数.</p>
</li>
<li><p><code>{function: {format: &quot;n&quot;}}</code> - 返回函数的名字，如果是匿名函数就返回空.</p>
</li>
<li><p><code>{function: {format: &quot;N&quot;}}</code> - 同小n，但当是匿名函数时返回 “anonymous”.</p>
</li>
</ul>
<p>一个例子, <code>{function {format: &quot;v n&quot;}}</code>, 将会生成函数运行结果和这个函数的名字.</p>
<h4 id="日期类型"><a href="#日期类型" class="headerlink" title="日期类型"></a>日期类型</h4><p>Date 类型和 <strong>MomentJS format</strong> 的处理方式很像, 通过很少的条件生成指定格式的字符串。 格式化所用到的条件有： U, G, I, L, T, 会分别生成 UTC, GTM, ISO, Local, 和 Time 字符串. 被删除不用的条件有: e-E,w-WW,g-GGGG,x.</p>
<p>通用的日期格式化和函数的格式化很像，只有一个参数。 例如： <code>{Date: {format: &lt;string spec&gt;}}</code>.</p>
<h3 id="更多用法"><a href="#更多用法" class="headerlink" title="更多用法"></a>更多用法</h3><p>分为三部分:</p>
<ol>
<li><strong>使用样式表</strong></li>
<li><strong>使用嵌入的条件表达式</strong></li>
<li><strong>垃圾回收</strong></li>
</ol>
<h4 id="使用样式表"><a href="#使用样式表" class="headerlink" title="使用样式表"></a>使用样式表</h4><p>所有的类型格式化都提供了一个可选的样式参数, 例如. <code>{number: {style: &#39;color:red&#39;}}</code>. 如果提供了这个参数，返回的结果将会被<code>&lt;span&gt;</code>包围，span中将包含所写的style。例如. <code>&lt;span style=&quot;color:red&quot;&gt;3&lt;/span&gt;</code>.</p>
<h4 id="使用嵌入的条件表达式"><a href="#使用嵌入的条件表达式" class="headerlink" title="使用嵌入的条件表达式"></a>使用嵌入的条件表达式</h4><p>任何的参数都可以包含这样的条件表达式<code>(&lt;condition&gt; ? &lt;result&gt; : &lt;else&gt;)</code>. 这些表达式的条件可以调用这两种内容<code>@value</code> or <code>@arguments[i]</code>，其内容将是引入将要被格式化的数据。</p>
<p>标准的使用方法是: <code>{number: {style: (@value &lt; 0 : &#39;color:red&#39;)}}</code></p>
<!--`@value` will dereference to the value of the argument being processed for the specific format specification, i.e. if it occurs in the second format specification of a format string, then `@value` will resolve to the 3rd argument to `StringFormatter.format`, since the format string itself is the first argument.

`@arguments[i]` will dereference to the argument in position i to 'StringFormatter.format'. This means that `@arguments[0]` will actually dereference to the format string itself.

Through the use of conditionals and styles, standard numeric color coding can be achieved, e.g. `{number: {style: (@value < 0 : 'color:red')}}`. Note, embedding the conditional within a string will not result in evaluation of the conditional, e.g. {`number: {style: 'font-weight:bold;(@value < 0 : 'color:red')'}}` will not work.-->

<p><strong>注意</strong>: 表达式不会被缓存并且也不会通过垃圾回收，所以使用条件表达式能够提高内存的利用。</p>
<h4 id="垃圾回收"><a href="#垃圾回收" class="headerlink" title="垃圾回收"></a>垃圾回收</h4><p>垃圾回收是根据StringFormatter的属性元素所决定的。</p>
<ul>
<li><p>StringFormatter.cache - 如果一个对象被格式化为字符串了，那么这个对象将会被缓存，以后其他的对象和缓存的对象相同，将会使用缓存中对象的格式化字符串。</p>
</li>
<li><p>StringFormatter.gcOn - 默认是true，如果想要禁止任何垃圾回收，就设置为false。</p>
</li>
<li><p>StringFormatter.hits - 格式化的次数</p>
</li>
<li><p>StringFormatter.gcThreshold = hits超过这个限额才会开始尝试垃圾回收。默认值是1000。</p>
</li>
<li><p>StringFormatter.gcPurgeLessThan = 缓存中少于该值命中次数的对象将会被清除，默认是1。</p>
</li>
<li><p>StringFormatter.gc() - 强制启动gc，即使没有到达gcThreshold</p>
</li>
</ul>
<h3 id="StringFormatter-JS的扩展"><a href="#StringFormatter-JS的扩展" class="headerlink" title="StringFormatter JS的扩展"></a>StringFormatter JS的扩展</h3><p>通过<code>StringFormatter.register(&lt;constructor&gt;,&lt;function&gt;,&lt;name string&gt;)</code>方法使得指定类可以自动使用 <code>StringFormatter</code> 。 如果没有提供 <code>&lt;function&gt;</code> , 类constructor 应当提供一个原型方法 <code>formatstring(formatSpec,formatter)&#39;</code> which will be called using the value of the currently processing argument as the<code>this</code>reference,<code>formatSpec</code>as the spec currently being processed, and<code>formatter</code>‘ as a reference to the <code>StringFormatter</code> object. 如果 <code>&lt;constructor&gt;</code> 是一个匿名的类或者其他,那么应当提供一个 <code>&lt;name string&gt;</code>.</p>
<p>自己的扩展应当保证能够正确的格式化指定类型，如果不能处理，应当抛出<code>TypeError</code>。</p>
<p>这里有一个日期格式化的例子，我们使用了新的方法和类型，从而不影响Date的原型:</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">DateFormat</span>(<span class="params">spec,date</span>) </span>&#123;</span><br><span class="line">  <span class="keyword">if</span>(!(date <span class="keyword">instanceof</span> <span class="built_in">Date</span>)) &#123;</span><br><span class="line">    <span class="keyword">throw</span> <span class="keyword">new</span> <span class="built_in">TypeError</span>(<span class="string">"Attempt to create DateFormat with non Date "</span> + <span class="built_in">JSON</span>.stringify(date));</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="keyword">this</span>.spec = spec;</span><br><span class="line">  <span class="keyword">this</span>.date = date;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">DateFormat.prototype.format = <span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">  <span class="keyword">if</span>(!<span class="keyword">this</span>.spec) &#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="keyword">this</span>.date.toString();</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="comment">// see source code of StringFormatter.js for more detail</span></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">dateFormatter</span>(<span class="params">spec</span>) </span>&#123;</span><br><span class="line">	<span class="keyword">var</span> dateformat = <span class="keyword">new</span> DateFormat(spec.format,<span class="keyword">this</span>);</span><br><span class="line">	<span class="keyword">return</span> dateformat.format();</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">StringFormatter.register(<span class="built_in">Date</span>,dateFormatter,<span class="string">"Date"</span>);</span><br></pre></td></tr></table></figure>

<p>翻译自<a rel="noopener" href="https://github.com/anywhichway/stringformatter/wiki" target="_blank">StringFormatter’Wiki</a></p>

      
    </div>
    
    
    

    

    

    
      <div>
        <ul class="post-copyright">
  <li class="post-copyright-author">
    <strong>本文作者：</strong>
    Gavin Zhang
  </li>
  <li class="post-copyright-link">
    <strong>本文链接：</strong>
    <a href="http://blog.gavinzh.com/2017/05/03/javascript-stringformatter-tutorial/" title="StringFormatter，一个javascript编写的字符串格式化库">http://blog.gavinzh.com/2017/05/03/javascript-stringformatter-tutorial/</a>
  </li>
  <li class="post-copyright-license">
    <strong>版权声明： </strong>
    本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/3.0/" rel="external nofollow" target="_blank">CC BY-NC-SA 3.0</a> 许可协议。转载请注明出处！
  </li>
</ul>

      </div>
    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/javascript/" rel="tag"># javascript</a>
          
            <a href="/tags/StringFormatter/" rel="tag"># StringFormatter</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2017/05/03/mosh-tutorial/" rel="next" title="mosh安装学习——一个基于UDP的ssh服务">
                <i class="fa fa-chevron-left"></i> mosh安装学习——一个基于UDP的ssh服务
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2017/05/04/vim-command/" rel="prev" title="vim-command">
                vim-command <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  
    <div class="comments" id="comments">
      <div id="disqus_thread">
        <noscript>
          Please enable JavaScript to view the
          <a href="https://disqus.com/?ref_noscript">comments powered by Disqus.</a>
        </noscript>
      </div>
    </div>

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image" src="https://avatars3.githubusercontent.com/u/5567916" alt="Gavin Zhang">
            
              <p class="site-author-name" itemprop="name">Gavin Zhang</p>
              <p class="site-description motion-element" itemprop="description"></p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/archives/">
              
                  <span class="site-state-item-count">129</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/categories/index.html">
                  <span class="site-state-item-count">7</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/tags/index.html">
                  <span class="site-state-item-count">158</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>
            

          </nav>

          
            <div class="feed-link motion-element">
              <a href="/atom.xml" rel="alternate">
                <i class="fa fa-rss"></i>
                RSS
              </a>
            </div>
          

          
            <div class="links-of-author motion-element">
                
                  <span class="links-of-author-item">
                    <a href="https://github.com/jiangmitiao" target="_blank" title="GitHub">
                      
                        <i class="fa fa-fw fa-github"></i>GitHub</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="mailto:me at gavinzh.com" target="_blank" title="E-Mail">
                      
                        <i class="fa fa-fw fa-envelope"></i>E-Mail</a>
                  </span>
                
            </div>
          

          
          

          
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-3"><a class="nav-link" href="#例子"><span class="nav-number">1.</span> <span class="nav-text">例子</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#通用使用方法"><span class="nav-number">2.</span> <span class="nav-text">通用使用方法</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#特殊的类型格式化"><span class="nav-number">3.</span> <span class="nav-text">特殊的类型格式化</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#字符串"><span class="nav-number">3.1.</span> <span class="nav-text">字符串</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#数值类型"><span class="nav-number">3.2.</span> <span class="nav-text">数值类型</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#布尔类型"><span class="nav-number">3.3.</span> <span class="nav-text">布尔类型</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#对象类型"><span class="nav-number">3.4.</span> <span class="nav-text">对象类型</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#数组类型"><span class="nav-number">3.5.</span> <span class="nav-text">数组类型</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#函数类型"><span class="nav-number">3.6.</span> <span class="nav-text">函数类型</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#日期类型"><span class="nav-number">3.7.</span> <span class="nav-text">日期类型</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#更多用法"><span class="nav-number">4.</span> <span class="nav-text">更多用法</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#使用样式表"><span class="nav-number">4.1.</span> <span class="nav-text">使用样式表</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#使用嵌入的条件表达式"><span class="nav-number">4.2.</span> <span class="nav-text">使用嵌入的条件表达式</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#垃圾回收"><span class="nav-number">4.3.</span> <span class="nav-text">垃圾回收</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#StringFormatter-JS的扩展"><span class="nav-number">5.</span> <span class="nav-text">StringFormatter JS的扩展</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      
        <div class="back-to-top">
          <i class="fa fa-arrow-up"></i>
          
            <span id="scrollpercent"><span>0</span>%</span>
          
        </div>
      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; 2013 &mdash; <span itemprop="copyrightYear">2020</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Gavin Zhang</span>

  

  
</div>





<div>
	<a href="http://www.beian.miit.gov.cn/" target="_blank">陕ICP备17010002号-1</a>
</div>





        




  <script type="text/javascript">
    (function() {
      var hm = document.createElement("script");
      hm.src = "//tajs.qq.com/stats?sId=61868582";
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
  </script>




  <div style="display: none;">
    <script src="//s95.cnzz.com/z_stat.php?id=1261805793&web_id=1261805793" language="JavaScript"></script>
  </div>



        
      </div>
    </footer>

    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>





  



  






  













  
  
    <script type="text/javascript" src="https://cdn.staticfile.org/jquery/3.4.1/jquery.min.js"></script>
  

  
  
    <script type="text/javascript" src="https://cdn.staticfile.org/fastclick/1.0.6/fastclick.js"></script>
  

  
  
    <script type="text/javascript" src="https://cdn.staticfile.org/jquery.lazyload/1.9.1/jquery.lazyload.min.js"></script>
  

  
  
    <script type="text/javascript" src="https://cdn.staticfile.org/velocity/2.0.5/velocity.min.js"></script>
  

  
  
    <script type="text/javascript" src="https://cdn.staticfile.org/velocity/2.0.5/velocity.min.js"></script>
  

  
  
    <script type="text/javascript" src="https://cdn.staticfile.org/fancybox/3.5.7/jquery.fancybox.min.js"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=6.0.0"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=6.0.0"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=6.0.0"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=6.0.0"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=6.0.0"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=6.0.0"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=6.0.0"></script>



  


  

    
      <script id="dsq-count-scr" src="https://zhang-hengs-website-blog.disqus.com/count.js" async></script>
    

    
      <script type="text/javascript">
        var disqus_config = function () {
          this.page.url = 'http://blog.gavinzh.com/2017/05/03/javascript-stringformatter-tutorial/';
          this.page.identifier = '2017/05/03/javascript-stringformatter-tutorial/';
          this.page.title = 'StringFormatter，一个javascript编写的字符串格式化库';
        };
        var d = document, s = d.createElement('script');
        s.src = 'https://zhang-hengs-website-blog.disqus.com/embed.js';
        s.setAttribute('data-timestamp', '' + +new Date());
        (d.head || d.body).appendChild(s);
      </script>
    

  




	





  














  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  
  <script src="https://cdn1.lncld.net/static/js/av-core-mini-0.6.4.js"></script>
  <script>AV.initialize("EhAMmIXTRGtethTcgYwA9afH-gzGzoHsz", "jzP1TaBhMleAUgPLXyB0h8oQ");</script>
  <script>
    function showTime(Counter) {
      var query = new AV.Query(Counter);
      var entries = [];
      var $visitors = $(".leancloud_visitors");

      $visitors.each(function () {
        entries.push( $(this).attr("id").trim() );
      });

      query.containedIn('url', entries);
      query.find()
        .done(function (results) {
          var COUNT_CONTAINER_REF = '.leancloud-visitors-count';

          if (results.length === 0) {
            $visitors.find(COUNT_CONTAINER_REF).text(0);
            return;
          }

          for (var i = 0; i < results.length; i++) {
            var item = results[i];
            var url = item.get('url');
            var time = item.get('time');
            var element = document.getElementById(url);

            $(element).find(COUNT_CONTAINER_REF).text(time);
          }
          for(var i = 0; i < entries.length; i++) {
            var url = entries[i];
            var element = document.getElementById(url);
            var countSpan = $(element).find(COUNT_CONTAINER_REF);
            if( countSpan.text() == '') {
              countSpan.text(0);
            }
          }
        })
        .fail(function (object, error) {
          console.log("Error: " + error.code + " " + error.message);
        });
    }

    function addCount(Counter) {
      var $visitors = $(".leancloud_visitors");
      var url = $visitors.attr('id').trim();
      var title = $visitors.attr('data-flag-title').trim();
      var query = new AV.Query(Counter);

      query.equalTo("url", url);
      query.find({
        success: function(results) {
          if (results.length > 0) {
            var counter = results[0];
            counter.fetchWhenSave(true);
            counter.increment("time");
            counter.save(null, {
              success: function(counter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(counter.get('time'));
              },
              error: function(counter, error) {
                console.log('Failed to save Visitor num, with error message: ' + error.message);
              }
            });
          } else {
            var newcounter = new Counter();
            /* Set ACL */
            var acl = new AV.ACL();
            acl.setPublicReadAccess(true);
            acl.setPublicWriteAccess(true);
            newcounter.setACL(acl);
            /* End Set ACL */
            newcounter.set("title", title);
            newcounter.set("url", url);
            newcounter.set("time", 1);
            newcounter.save(null, {
              success: function(newcounter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(newcounter.get('time'));
              },
              error: function(newcounter, error) {
                console.log('Failed to create');
              }
            });
          }
        },
        error: function(error) {
          console.log('Error:' + error.code + " " + error.message);
        }
      });
    }

    $(function() {
      var Counter = AV.Object.extend("Counter");
      if ($('.leancloud_visitors').length == 1) {
        addCount(Counter);
      } else if ($('.post-title-link').length > 1) {
        showTime(Counter);
      }
    });
  </script>



  

  
<script>
(function(){
    var bp = document.createElement('script');
    var curProtocol = window.location.protocol.split(':')[0];
    if (curProtocol === 'https') {
        bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';        
    }
    else {
        bp.src = 'http://push.zhanzhang.baidu.com/push.js';
    }
    var s = document.getElementsByTagName("script")[0];
    s.parentNode.insertBefore(bp, s);
})();
</script>


  
  

  
  


  
  <script type="text/javascript" src="/js/src/js.cookie.js?v=6.0.0"></script>
  <script type="text/javascript" src="/js/src/scroll-cookie.js?v=6.0.0"></script>


  

</body>
</html>
